<?php
// echo PHP_INT_MAX;
set_time_limit(0);
//generateFiles();
readInFileAndSort();
function generateFiles() {
	$sizes = getSizes();
	foreach ($sizes as $size) {
		$file = fopen('file_' . $size . '.txt', 'w+');
		for ($i = 0; $i < $size; $i++) {
			$randomNumber = getRandomFloatingPointNumber(-100000000, 100000000);
			if (($i+1) == $size) {
				fwrite($file, $randomNumber);
			} else {
				fwrite($file, $randomNumber . PHP_EOL);
			}
			 
		}
		
		fclose($file);
	}
}

function readInFileAndSort() {
	$file = 'file_1000.txt';
	
	$numbers = explode(PHP_EOL, file_get_contents($file));
	$numbers = array_map('floatval', $numbers);
	
	$start = microtime(true);
	sort($numbers);
	$end = microtime(true);
	var_dump($numbers);
	echo 'Sorting time: ' . ($end - $start) . ' (seconds)';
}

function getSizes() {
	$sizes = array();
	$number = 10;
	for ($i = 1; $i <= 5; $i++) {
		$number *= 10;
		$sizes[] = $number;
	}
	
	return $sizes;
}

function getRandomFloatingPointNumber($min, $max) {
	
	return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}

function task3($input) {
	$format = '%1$d = %2$s (control: %1$0' . (PHP_INT_SIZE * 8) . 'b)';
	$lsb = 1; // 00000000000100
	
	$binaryStringResult = '';
	
	if ($input <= PHP_INT_MAX && $input >= (-1)*PHP_INT_MAX) {
		$count = (PHP_INT_SIZE * 8);
		while ($count > 0) {
			if ($input & $lsb) {
				$binaryStringResult = '1' . $binaryStringResult;
			} else {
				$binaryStringResult = '0' . $binaryStringResult;
			}
			
			$lsb = $lsb << 1;
			$count--;
		}
		
		echo sprintf($format, $input, $binaryStringResult);
	}
}

/**
 * Bubble sort
 */
function task5($numbers) {
	$swapped = true;
	$size = count($numbers);
	while ($swapped) {
		$swapped = false;
		for ($i = 0; ($i+1) < $size; $i++) {
			if ($numbers[$i] > $numbers[$i+1]) {
				$numbers[$i] ^= $numbers[$i+1] ^= $numbers[$i] ^= $numbers[$i+1];
				$swapped = true;
			}
		}
	}
	
	return $numbers;
}

